<?php
namespace App\Services\Alibaba;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class Ali {
    /**
     * 阿里云内容安全检测
     *
     * @param [type] $content
     * @return void
     */
    public function green($content)
    {
        $body = $this->requestBody($content);
        AlibabaCloud::accessKeyClient(config('services.aliyun.accessKeyId'), config('services.aliyun.accessSecret'))
                        ->regionId('cn-hangzhou') // replace regionId as you need
                        ->asDefaultClient();

        try {
            $result = AlibabaCloud::roa()
                                ->product('Green')
                                ->scheme('http') // https | http
                                ->version('2018-05-09')
                                ->pathPattern('/green/text/scan')
                                ->method('POST')
                                ->options([
                                            'query' => [],
                                            ])
                                ->body($body)
                                ->request();
            $s = $result->toArray();
            if (isset($s['data'][0]['results'][0]['details'])) {
                return false;
            }
            return true;
        } catch (ClientException $e) {
            // echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            // echo $e->getErrorMessage() . PHP_EOL;
        }

    }

    protected function requestBody($content)
    {
        if (is_array($content)) {
            foreach($content as $v) {
                $tasks[] = [
                    'content' => $v,
                ];
            }
        } else {
            $tasks = [['content' => $content]];
        }
        $array = [
            'scenes' => ['antispam'],
            'tasks' => $tasks,
        ];
        return json_encode($array);
    }
}
